<?php
Yii::import('SolrUtil');
class GoodsManageController extends Controller
{

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(

            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('add','up','down','getlist','getbyid','delete','search'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }


	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		);
	}

    public function actionAdd()
    {
        $goods = new Goods();
        if(!empty($_POST['id']))$goods = Goods::model()->findByPk(new MongoId($_POST['id']));
        $goods->brand = $_POST["brand"];
        $goods->category = $_POST["category"];
        $goods->name_zn = $_POST["name_zn"];
        $goods->name_en = $_POST["name_en"];
        $goods->code = $_POST["code"];
        $goods->freight = (int)$_POST["freight"];
        $goods->size = $_POST["size"];
        $goods->icon = $_POST["icon"];
        $goods->shopimage = $_POST["shopimage"];
        $goods->images = $_POST["images"];
        if(isset($_POST["tags_en"]))$goods->tags_en = $_POST["tags_en"]; else $goods->tags_en = array();
        if(isset($_POST["tags_zn"]))$goods->tags_zn = $_POST["tags_zn"]; else $goods->tags_zn = array();
        $goods->shopaddress = $_POST["shopaddress"];
        $goods->originPrice = (int)$_POST["originPrice"];
        $goods->inventory = (int)$_POST["inventory"];
        $goods->shelfTime = time();//time(date($_POST["selfTime"]));
        $goods->placeOfOrigin_zn = $_POST["placeOfOrigin_zn"];
        $goods->placeOfOrigin_en = $_POST["placeOfOrigin_en"];
        $goods->technology_zn = $_POST["technology_zn"];
        $goods->technology_en = $_POST["technology_en"];
        $goods->material_zn = $_POST["material_zn"];
        $goods->material_en = $_POST["material_en"];
        $goods->desc_en = $_POST["desc_en"];

        $goods->categoryTag =  $_POST["categoryTag"];
        $goods->hours = $_POST["hours"];
        $goods->desc_zn = $_POST["desc_zn"];
        $goods->selling = false;
        $goods->status = 1;
        $goods->updatetime = time();


        $goods->save(false);
    }

    public function actionUp($id) {
        $goods = Goods::model()->findByPk(new MongoId($id));
        if ($goods->selling==true) return;

        $selling = $goods->selling;
        $shelftime = $goods->shelfTime;

        $goods->selling = true;
        $goods->shelfTime = time();
        $goods->save(false);
        try {
            $goodsAuction = new GoodsAuctioninfo();
            $goodsAuction->goods = $id;
            $goodsAuction->createtime = time();
            $goodsAuction->starttime = $goodsAuction->createtime;
            $goodsAuction->endtime = $goodsAuction->starttime + $goods->hours*60*60*1000;
            $goodsAuction->state =_GOODS_AUCTION_STATE_PROCESS;
            $goodsAuction->flowcode = $goods->code.'-'.'1';
            $goodsAuction->lowprice = $goods->originPrice;
            $goodsAuction->save(false);
        } catch (Exception $ex) {
            try {
                $goods->selling = $selling;
                $goods->shelfTime = $shelftime;
                $goods->save(false);
            } catch(Exception $ex) {
                Yii::getLogger()->log($ex->getMessage());
                //TODO 记录事务日志
            }
            echoToError(_ERROR_SYSTEM_FAULT);
        }
        try {
            RedisCacheUtil::writePrice($id,$goods->originPrice);
        } catch(Exception $ex) {
            try {
                $goods->selling = $selling;
                $goods->shelfTime = $shelftime;
                $goods->save(false);
            } catch(Exception $ex) {
                //TODO 记录事务日志
                Yii::getLogger()->log($ex->getMessage());
            }
            try {
                $goodsAuction->delete();
            } catch(Exception $ex) {
                //TODO 记录事务日志
                Yii::getLogger()->log($ex->getMessage());
            }
            echoToError(_ERROR_SYSTEM_FAULT);
        }

        $this->addToSolr($goods);
    }

    public function actionDown($id) {
        $goods = Goods::model()->findByPk(new MongoId($id));
        $goods->selling = false;
        $goods->save(false);

        $this->deleteFromSolr($id);
        RedisCacheUtil::deleteHotsCache($id);
    }

    public function actionSearch($name)
    {
        $resultColumn = array('name_en','_id');
        $query = array(
            'conditions' => array(
                'status' => array('>'=>0),
                'name_en'=>array('=='=>new MongoRegex("/^{$name}/i")),
                // 'code'=>array('>'=>10),
            ),
            'select'=>$resultColumn,
        );

        $result = Goods::model()->findAll($query);
        $records = array();
        if(!empty($result))
        {
            foreach ($result as $key => $value) {
                $value->_id = (string)$value->_id;
                foreach ($value as $key1=>$value1) {
                    if(!in_array($key1, $resultColumn))
                    {
                        unset($value[$key1]);
                    }
                }

                $obj['id'] = $value->_id;
                $obj['text'] = $value->name_en;
                array_push($records, $obj);
            }
        }

        echoStringToMobile(json_encode(array("results"=>$records)));

    }

    /**
     * 获得版本信息
     */
    public function actionGetList($iDisplayStart=0,$iDisplayLength=10,$search_name="",$search_code="",$brand=null)
    {
        $resultColumn = array('name_en','name_zn','selling','code');
        $query = array(
            'conditions' => array(
                'status'=>array('>'=>0),
                'name_zn'=>array('=='=>new MongoRegex("/^{$search_name}/i")),
                'code'=>array('=='=>new MongoRegex("/^{$search_code}/i")),
               // 'channel'=>array('=='=>constant("channel_homepage"))
            ),
            'select'=>$resultColumn,
            'limit'=>$iDisplayLength,
            'offset'=>$iDisplayStart,
        );

        if(!empty($brand))
            $query['conditions']['brand'] = array('=='=>$brand);

        $result = Goods::model()->findAll($query);

      
        $records = array();
        $records["aaData"] = array(); 

        if(!empty($result))
            foreach ($result as $key => $value) {
                $tmp = array();
                $value->_id = (string)$value->_id;

                foreach ($value as $key1=>$value1) {
                    if(in_array($key1, $resultColumn))
                    {
                        if($key1 == 'selling')
                            continue;
                        array_push($tmp, $value1);
                    }
                }

                if($value->selling)
                    array_push($tmp, '<a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs blue btn-editable"><i class="fa fa-pencil"></i> Edit</a>
                 <a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs red btn-removable"><i class="fa fa-times"></i> Delete</a> 
                 <a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs yellow btn-down"><i class="fa fa-times"></i> 下架</a>
                 <a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs red btn-rec"><i class="fa fa-times"></i> 推荐到首页</a> 
                  ');
                else
                    array_push($tmp, '<a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs blue btn-editable"><i class="fa fa-pencil"></i> Edit</a>
                 <a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs red btn-removable"><i class="fa fa-times"></i> Delete</a> 
                 <a href="javascript:;" data-id="'.$value->_id.'" class="btn btn-xs green btn-up"><i class="fa fa-times"></i> 上架</a> 
                  ');

                array_push($records["aaData"], $tmp);
            }

        $records["iTotalRecords"] = Goods::model()->count($query);
        $records["iTotalDisplayRecords"] = Goods::model()->count($query);
  
        echo json_encode($records);
    }

    public function actionGetById($id)
    {
        $goods = Goods::model()->findByPk(new MongoId($id));
        $goods->_id = (string)$goods->_id;
        $goods = $goods->toArray();
        $goods['brandname'] = Brand::model()->findByPk(new MongoId($goods['brand']))->name_en;
        $goods['categoryname'] = Category::model()->findByPk(new MongoId($goods['category']))->name_en;
        echoStringToMobile(json_encode($goods));
    }

    public function actionDelete($id)
    {
        $category = Goods::model()->findByPk(new MongoId($id));
        $category->status = -1;
        $category->save(false);

        $this->deleteFromSolr($id);

        RedisCacheUtil::delGoods($id);
    }

    private function addToSolr($goods)
    {
        $this->solrEn($goods);
        $this->solrZn($goods);
    }

    private function solrEn($goods)
    {
        $goods->_id = (string)$goods->_id;

        $price = RedisCacheUtil::getPrice($goods->_id);
        if(!$price) $price = $goods->originPrice;
        $solrUtil = new SolrUtil(_SOLR_ADDRESS, _SOLR_GOODS_EN);
        $solrUtil->update(array('id' => $goods->_id,'name'=>array('set'=>$goods->name_en),
            'desc'=>array('set'=>$goods->desc_en),
        'code'=>array('set'=>$goods->code),
        'technology'=>array('set'=>$goods->technology_en),
        'brandname'=>array('set'=>Brand::model()->findByPk(new MongoId($goods['brand']))->name_en),
        'originPrice'=>array('set'=>$goods->originPrice),
        'categoryname'=>array('set'=>Category::model()->findByPk(new MongoId($goods['category']))->name_en),
        'categorycode'=>array('set'=>Category::model()->findByPk(new MongoId($goods['category']))->code),
        'size'=>array('set'=>$goods->size),
        'material'=>array('set'=>$goods->material_en),
        'placeOfOrigin'=>array('set'=>$goods->placeOfOrigin_en),
        'shopaddress'=>array('set'=>$goods->shopaddress),
        'tags'=>array('set'=>$goods->tags_en),
        'icon'=>array('set'=>$goods->icon),
        'price'=>array('set'=>$price),
        'channel'=>array('set'=>_CHANNEL_GOODS)));
    }

    private function solrZn($goods)
    {
        $goods->_id = (string)$goods->_id;

        $price = RedisCacheUtil::getPrice($goods->_id);
        if(!$price) $price = $goods->originPrice;
        $solrUtil = new SolrUtil(_SOLR_ADDRESS, _SOLR_GOODS_ZN);
        $solrUtil->update(array('id' => $goods->_id,'name'=>array('set'=>$goods->name_zn),
        'desc'=>array('set'=>$goods->desc_zn),
        'code'=>array('set'=>$goods->code),
        'technology'=>array('set'=>$goods->technology_zn),
        'brandname'=>array('set'=>Brand::model()->findByPk(new MongoId($goods['brand']))->name_zn),
        'originPrice'=>array('set'=>$goods->originPrice),
        'categoryname'=>array('set'=>Category::model()->findByPk(new MongoId($goods['category']))->name_zn),
        'categorycode'=>array('set'=>Category::model()->findByPk(new MongoId($goods['category']))->code),
        'size'=>array('set'=>$goods->size),
        'material'=>array('set'=>$goods->material_zn),
        'placeOfOrigin'=>array('set'=>$goods->placeOfOrigin_zn),
        'shopaddress'=>array('set'=>$goods->shopaddress),
        'tags'=>array('set'=>$goods->tags_zn),
        'icon'=>array('set'=>$goods->icon),
        'price'=>array('set'=>$price),
        'channel'=>array('set'=>_CHANNEL_GOODS)));
    }

    private function deleteFromSolr($id)
    {
        $this->deleteZn($id);
        $this->deleteEn($id);
    }


    private function deleteEn($id)
    {
        $solrUtil = new SolrUtil(_SOLR_ADDRESS ,_SOLR_GOODS_EN);
        $solrUtil->delete(array('id'=>$id));
    }

    private function deleteZn($id)
    {
        $solrUtil = new SolrUtil(_SOLR_ADDRESS ,_SOLR_GOODS_ZN);
        $solrUtil->delete(array('id'=>$id));
    }

}